package org.opengauss.evaluate.utils;

import org.opengauss.evaluate.common.exception.ServiceException;

import java.io.File;

/**
 * @author biao.yang
 * @Description:
 * @date 2024/11/18 15:29
 */
public class FileUtils {

    public static void createAndClearDirectory(String path){
        File directory = new File(path);
        if (!directory.exists()) {
            boolean isCreated = directory.mkdirs();
            if (!isCreated) {
                throw new ServiceException(String.format("directory: %s create fail", path));
            }
        }else{
            //清空
            FileUtils.clearDirectory(directory);
        }
    }

    private static void clearDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    clearDirectory(file); // 递归清空子目录
                    file.delete(); // 删除子目录
                } else {
                    file.delete(); // 删除文件
                }
            }
        }
    }
}
